module repository.RedEnvelopeRepository;

import bootstrap.DatabaseBootstrap;
import hunt.entity;
import hunt.logging;
import std.conv : to;
import model;
import message.MsgDefine;
import core.stdc.time;
import message.Constants;
import service.IdGeneratorService;

import hunt.framework;

class RedEnvelopeRepository : EntityRepository!( RedEnvelope , int){

  this()
  {
    super( defaultEntityManager());
  }


  int addRedEnvelope(SendRedEnvelopeReq req ,ulong userId, EntityManager em)
  {

   // string id = IdGeneratorService.instance().getNextId();
    auto insert = em.createQuery!(RedEnvelope)("INSERT INTO RedEnvelope u (u.fromId,u.amount,u.number,u.status,u.created,u.chatId,u.message,u.type,u.taget_type,u.messageId) VALUES (:fromId,:amount,:number,:status,:created,:chatId,:message,:type,:taget_type,:messageId);");
    //insert.setParameter("id",to!int(id));
    insert.setParameter("fromId",userId);
    insert.setParameter("amount",req.amount);
    insert.setParameter("number",req.count);
    insert.setParameter("status",0); //0 正常 1领完 2过期
    insert.setParameter("created",core.stdc.time.time(null));
    insert.setParameter("chatId",req.target_id);
    insert.setParameter("message",req.wishes);
    insert.setParameter("type",req.type);
    insert.setParameter("taget_type",req.target_type);
    insert.setParameter("messageId",req.message_id);
    insert.exec();
    logInfo("addRedEnvelope id %s",insert.lastInsertId);
    return insert.lastInsertId;
  }


  RedEnvelope getStatus(int id)
  {
    scope(exit)
    {
      _manager.close();
    }
    auto query = _manager.createQuery!(RedEnvelope)("select * from RedEnvelope a where a.id = :id for update").
    setParameter("id", id);
    RedEnvelope[] objs = query.getResultList();
    if(objs.length != 0)
    {
        return objs[0];
    }else
    {
        return null;
    }
    //logInfo ("getUntreated size: %d",objs.length);
  }

  void updateStatus(int id)
  {
    scope(exit)
    {
      _manager.close();
    }
    auto update = _manager.createQuery!(RedEnvelope)("UPDATE RedEnvelope u SET u.status = 1 WHERE u.id = :id");
    update.setParameter("id",id);
    try{
      update.exec();
    }
    catch(Exception e)
    {
      logError("updateStatus error : %s",e.msg);
    }
  }


}
